package com.dongdongshop.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.Enum.ResultEnum;
import com.dongdongshop.constant.RedisNewsConst;
import com.dongdongshop.core.SpecificPrint;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.CartServiceI;
import com.dongdongshop.util.CookieUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("cart")
public class CartController {



   // @Reference(check=false ,timeout=106666)
    @Reference
    private CartServiceI cartServiceI;

    // 一、用户未登录
    // 二、用户已登录

    //操作cookie：web项目 负责前台之间数据交互
    //cart service 主要负责购物车业务逻辑


    @RequestMapping("cartList")
    public String cartList(HttpServletRequest request, HttpServletResponse response, Model model){
        List<Cart> cart = getCart(request, response);
        model.addAttribute("cartList",cart);
        return "cart";
    }



    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response){
        //获取登录用户
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();

        //从cookie获取购物车
        String carListValue = CookieUtils.getCookieValue(request, "cartList", "UTF-8");
    /*    Optional<String> optional = Optional.ofNullable(carListValue);
        carListValue = optional.orElse("[]");*/

        if(null == carListValue || "".equals(carListValue)){
            carListValue = "[]";
        }
        //将cookie中的数据转成list
        List<Cart> cartsCookie = JSONObject.parseArray(carListValue,Cart.class);

        //判断用户是否登录
        if(user == null){

            return cartsCookie;
        }else {
            List<Cart> cartsRedis =  cartServiceI.findCartListFromRedis(user.getUsername());

            if(cartsCookie.size() > 0){

                //合并购物车
                List<Cart> mergeList =  cartServiceI.mergeCarList(cartsCookie,cartsRedis);
                //将合并后的购物车存到redis
                cartServiceI.addToCartRedis(mergeList,user.getUsername());
                //删除本地cookie
                CookieUtils.deleteCookie(request,response, RedisNewsConst.cartList);
                return mergeList;
            }
                return cartsRedis;
        }

    }

    //往购物车中添加数据
    //添加成功后重定向到success-cart.html页面，并且展示刚刚添加的那件商品，要求显示title 和图片 和数量
    @RequestMapping("addToCart")
    public String addToCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num, Model model){
        //1.从cookie中获取购物车列表
        List<Cart> cartList = getCart(request, response);
        //2.调用cartservice组装购物车
        cartList = cartServiceI.addToCart(cartList,itemId,num);
        //获取登录用户
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        if(user == null){

            //3.将组装好的购物车数据写入cookie
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),60*60*24*30,"UTF-8");
        }else {
            cartServiceI.addToCartRedis(cartList,user.getUsername());
        }

        Cart cart = cartList.get(cartList.size() - 1);
        model.addAttribute("cartList",cart);
     //    return "success-cart";
        return "success-cart";
        /*  return SpecificPrint.response(ResultEnum.SUCCESS).setData(cartList);*/
    }

    //删除
    @RequestMapping("delCartOrderByItemId")
    @ResponseBody
    public  SpecificPrint delCartOrderByItemId(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num){
        //1、从cookie中获取购物车列表
        List<Cart> cartList = getCart(request, response);
        //调用cartservice组装购物车
        cartList = cartServiceI.addToCart(cartList,itemId,num);
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            //3、将组装好的购物车写入cookie中
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),60*60*24*30,"UTF-8");
        }else {
            cartServiceI.addToCartRedis(cartList,user.getUsername());
        }
        return SpecificPrint.response(ResultEnum.SUCCESS);
    }


    @RequestMapping("toListHomeIndex")
    public String toListHomeIndex(){
        return "home-index";
    }


    @RequestMapping("HomeSetting")
    public String HomeSetting(){
        return "home-setting-address";
    }
}


